package com.gable.common.util;

import com.gable.exhibition.model.User;
import com.gable.exhibition.view.UserView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jacky on 2018/2/5.
 * 缓存数据的class
 *
 */
@Component("cacheData")
public class CacheData {
    /**
     * 缓存当前用户的userMap
     * 主要用于缓存手机端
     */
    public static Map<Long,UserView> userMap = new HashMap<Long,UserView>();


    /**
     * 获取当前用户信息
     * @param userId  当前用户id
     * @param type    1、3.是手机端获取，2.是web获取
     * @return
     */
    public static UserView getSessionUser(Long userId,int type){

        if(userId != null && (type == 1 || type==3)){
            return userMap.get(userId);
        }
        UserView userView  = (UserView)getSession().getAttribute("loginUser");
        return  userView;
    }

    /**
     * 获取HttpSession对象
     * @return
     */
    public static HttpSession getSession() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
    }

    public static HttpServletRequest getRequest(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    /**
     * 插入用户登录信息
     * @param userView
     * @param type    1、3.是手机端获取，2.是web获取
     */
    public synchronized static void addSessionUser(UserView userView,int type){
        if(type == 1 || type==3){
           /* if(userMap.containsKey(userView.getUserId())){
                return;
            }*/
            userMap.put(userView.getUserId(),userView);
        }else{
            getSession().setAttribute("loginUser",userView);
        }
    }

    /**
     * 登录退出，清除缓存信息
     * @param userId
     */
    public synchronized static void deleteSessionUser(Long userId){
        if(userMap.containsKey(userId)){
            userMap.remove(userId);
        }
        getSession().invalidate();
    }

}
